# _*_ coding : utf-8 _*_
# @Time : 2024-05-29 13:34
# @Author : haowen
# @File : 9.数据训练
# @Project : face identifying
import os
import cv2
from PIL import Image
import numpy as np

def getImageAndLabels(path):
    # 保存人脸数据
    facesSamples = []
    # 保存姓名数据
    ids = []
    # 存储图片信息
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
    # 加载分类器
    face_detect = cv2.CascadeClassifier("./haarcascade_frontalface_alt2.xml")
    # 遍历图片
    for imagePath in imagePaths:
        # 打开图片 灰度化 PIL
        PIL_img = Image.open(imagePath).convert('L')
        # 图片->数组
        img_numpy = np.array(PIL_img,'uint8')
        # 保存图片人脸特征
        faces = face_detect.detectMultiScale(img_numpy)
        # 获取id和姓名
        id = int(os.path.split(imagePath)[1].split('.')[0])

        # 预防无面容图片
        for x,y,w,h in faces:
            ids.append(id)
            facesSamples.append(img_numpy[y:y+h,x:x+w])
        print('id:', id)
        print('fs:', facesSamples)
    return facesSamples,ids

if __name__ == '__main__':
    path = './data'
    # 获取图像数组和id标签数组
    faces,ids = getImageAndLabels(path)
    # 加载识别器
    recognizer = cv2.face.LBPHFaceRecognizer.create()
    # 训练
    recognizer.train(faces,np.array(ids))

    recognizer.write('./trainer/trainer.yml')